import json

from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect,JsonResponse
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt

from utils.getPublicData import *
from utils.querymysql import *
from utils.getChartData import *
import logging
from.models import UserBehavior



# Create your views here.
def home(request):
    if request.method == 'GET':
        averageCityX, averageCityY, salaryCategoryData, expSalaryX, expSalaryY1, expSalaryY2, peopleCategoryData, addressSumData, sorted_arr = getIndexData()
        print("Sorted array format:", sorted_arr)  # 添加调试信息
        return render(request, 'home.html', {
            'averageCityX': averageCityX,
            'averageCityY': averageCityY,
            'salaryCategoryData': salaryCategoryData,
            'expSalaryX': expSalaryX,
            'expSalaryY1': expSalaryY1,
            'expSalaryY2': expSalaryY2,
            'peopleCategoryData': peopleCategoryData,
            'addressSumData': addressSumData,
            'sorted_arr': sorted_arr
        })


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html', {})
    else:
        uname = request.POST.get('username')
        password = request.POST.get('password')
        print(uname, password)
        try:
            user = User.objects.get(username=uname, password=password)
            request.session['username'] = uname
            return redirect('/myApp/home/')
        except:
            messages.error(request, '请输入正确的用户名与密码')
            return HttpResponseRedirect('/myApp/login/')
        # return render(request, 'login.html', {})


def registry(request):
    if request.method == 'GET':
        return render(request, 'register.html', {})
    else:
        uname = request.POST.get('username')
        password = request.POST.get('password')
        confirmPassword = request.POST.get('confirmPassword')
        print(uname, password, confirmPassword)
        try:
            User.objects.get(username=uname)
            message = '用户名已被注册'
        except:
            if not uname or not password or not confirmPassword:
                message = '注册信息不能为空'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/registry/')
            elif password != confirmPassword:
                message = '两次密码不相符，请重新输入'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/registry/')
            else:
                User.objects.create(username=uname, password=password)
                messages.error(request, '注册成功！')
                return HttpResponseRedirect('/myApp/login/')
        return render(request, 'register.html', {})


def logOut(request):
    request.session.clear()
    return redirect('/myApp/login/')


def salaryChar(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)

        selectList = ['0-5k', '5-7k', '7-10k', '10-20k', 'above_20k']
        defaultse = request.GET.get('range') or '5-7k'
        typeSalaryList = list(gettypeSalary(range=defaultse))
        print(typeSalaryList)
        
        # 获取职位类型作为X轴数据和图例
        typeSalaryX = [x['type'] for x in typeSalaryList]
        # 获取薪资数据
        typeSalaryData = [x[defaultse] for x in typeSalaryList]

        print(typeSalaryX)
        averageTypeList = list(getaverageType())
        averageTypeData = []
        for i in averageTypeList:
            averageTypeData.append({
                'name': i['type'],
                'value': float(round(i['avg_max_salary'], 2)),
            })
            
        return render(request, 'index.html', {
            'userInfo': userInfo,
            'typeSalaryX': typeSalaryX,
            'typeSalaryData': typeSalaryData,
            'averageTypeData': averageTypeData,
            'selectList': selectList,
            'defaultse': defaultse
        })


def educationChar(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)
        averageExperienceList = list(getaverageExperience())
        averageExperienceX = [x['workExperience'] for x in averageExperienceList]
        averageExperienceY1 = [round(float(x['avg_max_salary']),1) for x in averageExperienceList]
        averageExperienceY2 = [int(x['count']) for x in averageExperienceList]
        print(averageExperienceX,averageExperienceY1,averageExperienceY2)

        educationCountList = list(geteducationCount())
        educationData = []
        for i in educationCountList[:-1]:
            educationData.append({
                'name': i['educational'],
                'value': i['count'],
                'unit':'人'
            })
        print(educationData)
        return render(request, 'educationChar.html', {
            'userInfo': userInfo,
            'averageExperienceX': averageExperienceX,
            'averageExperienceY1': averageExperienceY1,
            'averageExperienceY2': averageExperienceY2,
            'educationCountData': educationData,
        })

def industryChar(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)

        typeCountList = list(gettypeCount())
        typeCountX = [x['type'] for x in typeCountList]
        typeCountY = [x['count'] for x in typeCountList]

        typeMaxList = list(gettypeMax())
        typeMaxData = []
        for i in typeMaxList:
            typeMaxData.append({
                'name': i['type'],
                'value': i['max_salary'],
            })
        print(typeCountX,typeCountY,typeMaxData)
        return render(request, 'industryChar.html', {
            'userInfo': userInfo,
            'typeCountX': typeCountX,
            'typeCountY': typeCountY,
            'typeMaxData': typeMaxData,

        })

def cityChar(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)

        citySalaryList = list(getcitySalary())

        selectList = [x['city'] for x in citySalaryList]
        defaultCity = request.GET.get('city') or '苏州'
        print(defaultCity)
        citySalaryX = ['0-5k','5-7k','7-10k','10-20k','20k以上']
        
        # 添加缓存
        cache_key = f'city_salary_{defaultCity}'
        citySalaryY = []
        city_data = get_cached_query(cache_key,
                                   'SELECT * FROM citySalary WHERE city = %s',
                                   [defaultCity])[0]
        citySalaryY = [
            city_data['0-5k'],
            city_data['5-7k'],
            city_data['7-10k'],
            city_data['10-20k'],
            city_data['above_20k']
        ]
        
        # 添加缓存
        cache_key = f'city_people_{defaultCity}'
        cityPeopleData = get_cached_query(cache_key,
                                        'SELECT * FROM cityPeople WHERE city = %s',
                                        [defaultCity])[0]
        
        cityPeopleReal = [
            {
                'name':'0-20人',
                'value':cityPeopleData['0-19']
            },{
                'name':'20-100人',
                'value':cityPeopleData['20-99']
            },{
                'name':'100-500人',
                'value':cityPeopleData['100-499']
            },{
                'name':'500-1000人',
                'value':cityPeopleData['500-999']
            },{
                'name':'1000-10000人',
                'value':cityPeopleData['1000-9999']
            },{
                'name':'10000人以上',
                'value':cityPeopleData['above_10000']
            }
        ]
        print(cityPeopleReal,citySalaryX,citySalaryY)
        return render(request, 'cityChar.html', {
            'userInfo': userInfo,
            'selectList': selectList,
            'defaultCity': defaultCity,
            'cityPeopleReal': cityPeopleReal,
            'citySalaryX': citySalaryX,
            'citySalaryY': citySalaryY
        })

def tableData(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)
        
        # 获取原始数据（字典列表）
        raw_table_data = list(getjobData1())
        
        # 转换为二维列表，按照模板中的展示顺序
        tableData = []
        for item in raw_table_data:
            row = [
                item['type'],                  # 类型 (i.0)
                item['title'],                 # 名称 (i.1)
                item['companyTitle'],          # 公司名称 (i.2)
                item['minSalary'],             # 最低薪资 (i.3)
                item['maxSalary'],             # 最高薪资 (i.4)
                item['workExperience'],        # 工作经验 (i.5)
                item['educational'],           # 学历要求 (i.6)
                item['detailUrl'],             # 详情链接 (i.7)
                item['companyPeople'],         # 公司规模 (i.8)
                item['workTag'],               # 工作标签 (i.9)
                item['welfare'],               # 福利待遇 (i.10)
                item['imgSrc'],                # 图标 (i.11)
                item['city'],                  # 城市 (i.12)
                item['id'],                    # ID (i.13)
                item['experience_value'],      # 工作经验转化 (i.14)
            ]
            tableData.append(row)
        
        print("Converted table data format:", tableData[:1])  # 打印第一行数据用于调试
        
        return render(request, 'tableData.html', {
            'userInfo': userInfo,
            'tableData': tableData
        })

def collectData(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)
        jobList = getUserHistory(userInfo)
        print(jobList)
        return render(request, 'collectData.html', {
            'userInfo': userInfo,
            'jobList': jobList
        })

def addHistory(request,jobId):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    addHistoryData(userInfo,jobId)
    return HttpResponseRedirect('/myApp/collectData')

def delHistory(request,jobId):
    data = History.objects.filter(jobId=jobId)
    data.delete()
    return HttpResponseRedirect('/myApp/collectData')

def changeInfo(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    if request.method == 'POST':
        print(request.POST)
        res = changePwd(userInfo,request.POST)
        if res != None:
            messages.error(request,res)
            return HttpResponseRedirect('/myApp/changeInfo')
        userInfo = User.objects.get(username=uname)
        messages.success(request,'修改成功')
    return render(request, 'changeInfo.html', {
        'userInfo': userInfo,
    })

def titleCloud(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)

        return render(request, 'titleCloud.html', {
            'userInfo': userInfo,

        })

def tagCloud(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)

        return render(request, 'tagCloud.html', {
            'userInfo': userInfo,

        })

def recommendPage(request):
    if request.method == 'GET':
        uname = request.session.get('username')
        userInfo = User.objects.get(username=uname)
        
        # 获取历史数据和点击数据
        dataList = list(History.objects.filter(user=userInfo).order_by('-count'))
        behavior_countData = list(UserBehavior.objects.filter(user=userInfo).order_by('-behavior_count'))
        
        # 处理点击数据 - 获取前40%的高点击数据
        top_behavior_count_count = int(len(behavior_countData) * 0.4)
        top_behavior_counts = behavior_countData[:top_behavior_count_count]
        
        # 合并数据并转换格式
        user_behavior_data = []
        
        # 添加历史数据
        for history in dataList:
            user_behavior_data.append({'jid': int(history.jobId)})
            
        # 添加高点击数据
        for behavior in top_behavior_counts:
            behavior_dict = {'jid': behavior.id}
            if behavior_dict not in user_behavior_data:
                user_behavior_data.append(behavior_dict)
        
        # 如果没有用户行为数据，返回空推荐
        if not user_behavior_data:
            return render(request, 'recommendPage.html', {
                'userInfo': userInfo,
                'recommendList': []
            })
        
        # 调用推荐算法
        from algorithmPool.recommend.spectralCluster import ContentBasedRecall, SpectralReranker
        from utils.getPublicData import getjobData
        
        # 初始化推荐系统
        recall_system = ContentBasedRecall()
        recall_results = recall_system.get_recall(user_behavior_data)
        
        # 使用光谱聚类重排序
        spectral_reranker = SpectralReranker()
        final_results = spectral_reranker.rerank(recall_results, user_behavior_data)
        
        # 获取所有职位数据
        all_jobs = {str(job['id']): job for job in getjobData()}  # 确保id是字符串类型
        
        # 直接构建二维列表
        recommendList = []
        for job in final_results:
            jid = str(job['jid'])  # 确保jid是字符串类型
            if jid in all_jobs:
                job_data = all_jobs[jid]
                # 按照数据库表的字段顺序构建列表
                job_list = [
                    job_data['type'],            # 职位类型
                    job_data['title'],           # 职位标题
                    job_data['companyTitle'],    # 公司名称
                    job_data['minSalary'],       # 最低薪资
                    job_data['maxSalary'],       # 最高薪资
                    job_data['workExperience'],  # 工作经验
                    job_data['educational'],      # 教育背景
                    job_data['detailUrl'],       # 详情链接
                    job_data['companyPeople'],   # 公司规模
                    job_data['workTag'],         # 工作标签
                    job_data['welfare'],         # 福利
                    job_data['imgSrc'],          # 图片链接
                    job_data['city'],            # 城市
                    job_data['id'],              # ID
                    job_data['experience_value']  # 经验值（如果有的话）
                ]
                recommendList.append(job_list)
        
        print(recommendList)
        return render(request, 'recommendPage.html', {
            'userInfo': userInfo,
            'recommendList': recommendList
        })



logger = logging.getLogger(__name__)

@csrf_exempt
def record_user_behavior(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)  # 安全地解析前端传来的JSON数据
            behavior_type = data.get('behavior')
            data_id = data.get('dataId')
            uname = request.session.get('username')
            userInfo = User.objects.get(username=uname)


            if behavior_type == 'behavior_count':
                # 尝试获取已存在的该用户对该数据项的行为记录
                user_behavior, created = UserBehavior.objects.get_or_create(
                    user=userInfo,
                    id=data_id,
                    behavior_type=behavior_type,
                    defaults={'behavior_count': 0}  # 如果不存在则创建，初始点击次数设为0
                )
                user_behavior.behavior_count += 1  # 点击次数加1
                user_behavior.save()
                print(user_behavior.behavior_count)
                return JsonResponse({'status':'success', 'behavior_count_count': user_behavior.behavior_count})
            else:
                return JsonResponse({'status': 'invalid_behavior_type'})
        except json.JSONDecodeError as e:
            logger.error(f'解析用户行为数据出现JSON解析错误：{e}')
            return JsonResponse({'status': 'error'})
        except Exception as e:
            logger.error(f'处理用户行为数据出现其他错误：{e}')
            return JsonResponse({'status': 'error'})
    return JsonResponse({'status': 'error'})
